package com.seari.custody.config;

import com.seari.custody.component.UserDetailsServiceImpl;
import com.seari.custody.mapper.UserMapper;
import com.seari.custody.util.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UserDetailsServiceImpl userDetailsService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        UserDetails userInfo = userDetailsService.loadUserByUsername(userName);

        boolean isValid = false;
        try {
            isValid = Objects.equals(EncryptUtils.encode(password), userInfo.getPassword());
        } catch (Exception e) {
            log.error(e.getMessage());

            throw new BadCredentialsException("验证密码失败");
        }
        // 验证密码
        if (!isValid) {
            throw new BadCredentialsException("密码错误！");
        }

        return new UsernamePasswordAuthenticationToken(userInfo, password, null);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}